﻿using MCPlatform.UI.Components;
using MCPlatform.UI.Controls.Models;
using Microsoft.Win32;
using Panuon.WPF.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Shapes;
using System.Windows;
using System.Xml.Linq;
using System.IO;
using Path = System.IO.Path;
using System.Collections.ObjectModel;
using MCPlatform.Dxf.Factories;
using MCPlatform.Dxf.Readers;
using MCPlatform.Shared.DAL.Contexts;
using Azure;
using MCPlatform.Shared.DAL.Models;
using MCPlatform.Models;
using MCPlatform.MotionLib.Base.AssitantClass;
using MCPlatform.MotionLib.Base.Environment;
using Microsoft.VisualBasic;
using Microsoft.AspNetCore.Hosting.Server;
using LiveChartsCore.Defaults;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore;
using LiveChartsCore.SkiaSharpView.Painting;
using SkiaSharp;
using LiveChartsCore.SkiaSharpView.VisualElements;
using LiveChartsCore.SkiaSharpView.Extensions;
using System.Data;
using System.Reflection;



namespace MCPlatform.ViewModels.Shell
{
    
    public class DataTableViewModel : ViewModelBase
    {
        #region Properties

        /// <summary>
        /// 产品类型集合
        /// </summary>
        public ObservableCollection<ProductModel> ProductModels { get; set; } = new ObservableCollection<ProductModel>();

        public ProductModel SelectedItem
        {
            get { return _selectedItem; }
            set
            {               
                Set(ref _selectedItem, value);
              
            }
        }
        private ProductModel _selectedItem = new ProductModel();

        /// <summary>
        /// Datagrid 数据源
        /// </summary>
        public ObservableCollection<ProductionDataModel> ProductionData
        {
            get { return _productionData; }
            set
            {
                Set(ref _productionData, value);
            }
        }
        private ObservableCollection<ProductionDataModel> _productionData = new ObservableCollection<ProductionDataModel>();

        private string _selectedTimeValve= string.Empty;

        public string SelectedTimeValue
        {
            get { return _selectedTimeValve; }
            set 
            { 
                Set(ref _selectedTimeValve, value);
               
            }
        }


       
        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartTime
        {
            get { return _startTime; }
            set 
            { 
                Set(ref _startTime, value);
               
            }
        }
        private DateTime _startTime;


        /// <summary>
        /// 结束时间
        /// </summary>
        public DateTime EndTime
        {
            get { return _endTime; }
            set
            {
                Set(ref _endTime, value);

            }
        }
        private DateTime _endTime;




        #region OEE
        public LabelVisual OEETitle { get; set; } =
        new LabelVisual
        {
            Text = "OEE Over Time",
            TextSize = 15,
            Padding = new LiveChartsCore.Drawing.Padding(10),
            Paint = new SolidColorPaint(SKColors.Blue),
            
        };


        public ISeries[] OEESeries { get; set; } =
        {
           
            new LineSeries<DateTimePoint>
            {
                
                Values = new ObservableCollection<DateTimePoint>
                {
                    new DateTimePoint(new DateTime(2021, 1, 1,05,30,15), 3),
                    new DateTimePoint(new DateTime(2021, 1, 1,06,30,15), 6),
                    new DateTimePoint(new DateTime(2021, 1, 1,07,30,15), 7),
                    new DateTimePoint(new DateTime(2021, 1, 1,08,30,15), 4),
                    new DateTimePoint(new DateTime(2021, 1, 1,09,30,15), 8),
                    new DateTimePoint(new DateTime(2021, 1, 1,10,30,15), 5),
                    new DateTimePoint(new DateTime(2021, 1, 1,13,30,15), 3),
                },
               
               
            }
        };

        public Axis[] OEEXAxes { get; set; } =
        {
             new DateTimeAxis(TimeSpan.FromMinutes(1), date => date.ToString("MM/dd HH:mm"))
             {
                 
                 //NamePaint = new SolidColorPaint(SKColors.Red),

                 //LabelsPaint = new SolidColorPaint(SKColors.Blue),
             }
            
        };

        #endregion


        #region Output

        public LabelVisual OutputTitle { get; set; } =
        new LabelVisual
        {
            Text = "Output Over Time",
            TextSize = 15,
            Padding = new LiveChartsCore.Drawing.Padding(10),
            Paint = new SolidColorPaint(SKColors.Blue),

        };


        public ISeries[] OutputSeries { get; set; } =
        {

            new ColumnSeries<DateTimePoint>
            {

                Values = new ObservableCollection<DateTimePoint>
                {
                    new DateTimePoint(new DateTime(2021, 1, 1,05,30,15), 3),
                    new DateTimePoint(new DateTime(2021, 1, 1,06,30,15), 6),
                    new DateTimePoint(new DateTime(2021, 1, 1,07,30,15), 7),
                    new DateTimePoint(new DateTime(2021, 1, 1,08,30,15), 4),
                    new DateTimePoint(new DateTime(2021, 1, 1,09,30,15), 8),
                    new DateTimePoint(new DateTime(2021, 1, 1,10,30,15), 5),
                    new DateTimePoint(new DateTime(2021, 1, 1,13,30,15), 3),
                },


            }
        };

        public Axis[] OutputXAxes { get; set; } =
        {
             new DateTimeAxis(TimeSpan.FromDays(1), date => date.ToString("MM/dd"))
             {
                 MinStep = TimeSpan.FromDays(1).Ticks,
                 //NamePaint = new SolidColorPaint(SKColors.Red),

                 //LabelsPaint = new SolidColorPaint(SKColors.Blue),
             }

        };


        #endregion

       
        public IEnumerable<ISeries> ProductionPieSeries 
        {
            get => _productionPieSeries;
            set
            {
                Set(ref _productionPieSeries, value);
            }
        }
        public IEnumerable<ISeries> _productionPieSeries =
         new[] { 2, 4, 1, 4, 3 }.AsPieSeries();


        public LabelVisual ProductionPieTitle { get; set; } =
           new LabelVisual
           {
               Text = "Production Type Proportion",
               TextSize = 15,
               Padding = new LiveChartsCore.Drawing.Padding(10),
               Paint = new SolidColorPaint(SKColors.Blue)
           };


        #endregion


        #region CTOR

        public DataTableViewModel()
        {
            Load();
        }

        #endregion



        #region Methods


        public void GetData()
        {
            try
            {
                var timespan = SelectedTimeValue;

                if (timespan.Contains("当天"))
                {
                    LoadTodayData();
                }
                else if (timespan.Contains("当月"))
                {
                    LoadMonthlyData();
                }
                else
                {
                    LoadCustomDateRangeData();
                }



                UpdateOEESeries();

                UpdateOutputSeries();


                UpdateProductionPieSeries();
            }
            catch (Exception e)
            {
                Logger.Error(e,e.Message);
                MessageBoxX.Show(e.Message);
                return;
                //throw;
            }
            
            //var productionData = new ProductionDataContext();
            // DateTime dateTime = DateTime.Now;
            // var data = productionData.ReadFirst();

            //ProductionDataModel productionMode = new ProductionDataModel()
            // {

            //     StartTime = dateTime,
            //     ProductionType = "830x260",
            //     Operator = "Operator",
            //     MachineUpTime = TimeSpan.FromHours(1),
            //     ProductionTime = TimeSpan.FromMinutes(20),
            //     DownTime = TimeSpan.FromMinutes(40),
            //     Output = 200,
            //     OEE = 98.2,
            //     UPH = 150,
            //     Yield = 99.9,
            //     LastUpdated = System.DateTime.Now,
            // };

            // productionData.Add(productionMode);

            // productionData.Delete(productionMode);
        }


        public  void ExportData()
        {
            DataTable dataTable = ConvertToDataTable(ProductionData);
            System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
            saveFileDialog.Filter = "CSV文件 (*.csv)|*.csv";
            saveFileDialog.Title = "选择保存路径和文件名";

            if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                StringBuilder csvContent = new StringBuilder();

                if (dataTable == null)
                {
                    MessageBoxX.Show("导出失败！数据为空！", "提示",icon:MessageBoxIcon.Warning);
                    return;
                }

                // 写入表头
                foreach (DataColumn column in dataTable.Columns)
                {
                    csvContent.Append(column.ColumnName + ",");
                }
                csvContent.AppendLine();

                // 写入数据行
                foreach (DataRow row in dataTable.Rows)
                {
                    foreach (var item in row.ItemArray)
                    {
                        csvContent.Append(item?.ToString() + ",");
                    }
                    csvContent.AppendLine();
                }

                // 将数据写入 CSV 文件
                File.WriteAllText(saveFileDialog.FileName, csvContent.ToString(), Encoding.UTF8);

                MessageBoxX.Show("导出成功！", icon: MessageBoxIcon.Success);
            }
        }


        public void Load()
        {
            var productConfigs = ReadConfigData.GetParaConfigs<ProductModel>(Paths.ProductConfigPaths);

            if (productConfigs != null)
            {
                ProductModels = new ObservableCollection<ProductModel>(productConfigs);
                ProductModel allModel = new ProductModel() { ControlName = "All" };
                ProductModels.Add(allModel);
                SelectedItem = allModel;

            }

        }



        private void LoadTodayData()
        {
            try
            {
                using (var context = new ProductionDataContext())
                {
                    var today = DateTime.Today;

                    if (SelectedItem.ControlName != "All")
                    {
                        var data = context.ProductionDataEntities
                                          .Where(e => e.StartTime >= today && e.StartTime < today.AddDays(1)
                                                      && e.ProductionType != null
                                                      && e.ProductionType.Contains(SelectedItem.ControlName))
                                          .ToList();

                        ProductionData = new ObservableCollection<ProductionDataModel>(data);
                    }
                    else
                    {
                        var data = context.ProductionDataEntities
                                          .Where(e => e.StartTime >= today && e.StartTime < today.AddDays(1))
                                          .ToList();

                        ProductionData = new ObservableCollection<ProductionDataModel>(data);
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
            
        }



        private void LoadMonthlyData()
        {
            try
            {
                using (var context = new ProductionDataContext())
                {
                    var today = DateTime.Today;
                    var firstDayOfMonth = new DateTime(today.Year, today.Month, 1);
                    var firstDayOfNextMonth = firstDayOfMonth.AddMonths(1);

                    if (SelectedItem.ControlName != "All")
                    {
                        var data = context.ProductionDataEntities
                                          .Where(e => e.StartTime >= firstDayOfMonth && e.StartTime < firstDayOfNextMonth
                                                      && e.ProductionType != null
                                                      && e.ProductionType.Contains(SelectedItem.ControlName))
                                          .ToList();

                        ProductionData = new ObservableCollection<ProductionDataModel>(data);
                    }
                    else
                    {
                        var data = context.ProductionDataEntities
                                          .Where(e => e.StartTime >= firstDayOfMonth && e.StartTime < firstDayOfNextMonth)
                                          .ToList();

                        ProductionData = new ObservableCollection<ProductionDataModel>(data);
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
           
        }


        private void LoadCustomDateRangeData()
        {
            try
            {
                if (StartTime > EndTime)
                {
                    MessageBoxX.Show("结束时间不能大于开始时间", "提示", MessageBoxIcon.Info);
                    return;
                }
                else if (EndTime - StartTime > TimeSpan.FromDays(60))
                {
                    MessageBoxX.Show("选择时间太长，时间跨度不能大于60天！", "提示", MessageBoxIcon.Info);
                    return;
                }

                using (var context = new ProductionDataContext())
                {
                    if (SelectedItem.ControlName != "All")
                    {
                        var data = context.ProductionDataEntities
                                          .Where(e => e.StartTime >= StartTime && e.StartTime <= EndTime
                                                      && e.ProductionType != null
                                                      && e.ProductionType.Contains(SelectedItem.ControlName))
                                          .ToList();

                        ProductionData = new ObservableCollection<ProductionDataModel>(data);
                    }
                    else
                    {
                        var data = context.ProductionDataEntities
                                          .Where(e => e.StartTime >= StartTime && e.StartTime <= EndTime)
                                          .ToList();

                        ProductionData = new ObservableCollection<ProductionDataModel>(data);
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
           
        }


        public void UpdateProductionPieSeries()
        {
            var groupedData = ProductionData
             .GroupBy(p => p.ProductionType)
             .Select(g => new
                 {
                      ProductionType = g.Key,
                     TotalOutput = g.Sum(p => p.Output)
                 })
             .ToList();

            var totalOutput = groupedData.Sum(g => g.TotalOutput);

            ProductionPieSeries = groupedData
                .Select(data => new PieSeries<int>
                {
                    Values = new[] { data.TotalOutput },
                    Name = data.ProductionType,
                    DataLabelsPaint = new SolidColorPaint(SKColors.Black), // 设置标签颜色
                    DataLabelsFormatter = point => $"{data.ProductionType} ({data.TotalOutput / (double)totalOutput:P})",
                    Pushout=5,
                })
                .ToArray();

        }


        public void UpdateOEESeries()
        {
            // 先清空现有数据
            if (OEESeries[0].Values is ObservableCollection<DateTimePoint> values)
            {
                values.Clear();

                // 添加新的数据
                foreach (var data in ProductionData)
                {
                    values.Add(new DateTimePoint(data.StartTime, data.OEE));
                }
            }

        }


        public void UpdateOutputSeries()
        {
            // 先清空现有数据
            if (OutputSeries[0].Values is ObservableCollection<DateTimePoint> outputs)
            {
                outputs.Clear();

                var groupedData = ProductionData
                    .GroupBy(p => p.LastUpdated.Date)
                    .Select(g => new DateTimePoint(g.Key, g.Sum(p => p.Output)))
                    .ToList();



                //添加新的数据
                foreach (var data in groupedData)
                {
                    outputs.Add(new DateTimePoint(data.DateTime, data.Value));
                }
            }
        }



        public DataTable ConvertToDataTable<T>(ObservableCollection<T> items) where T : class
        {
            DataTable dataTable = new DataTable();

            // 获取泛型类 T 的所有属性
            PropertyInfo[] properties = typeof(T).GetProperties();

            // 为 DataTable 添加列，列名为属性名
            foreach (PropertyInfo property in properties)
            {
                dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
            }

            // 遍历 ObservableCollection<T> 并填充 DataTable
            foreach (T item in items)
            {
                DataRow row = dataTable.NewRow();

                foreach (PropertyInfo property in properties)
                {
                    row[property.Name] = property.GetValue(item) ?? DBNull.Value;
                }

                dataTable.Rows.Add(row);
            }

            return dataTable;
        }

        #endregion


    }
}